// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command
const $ = _.aggregate

/**
 * 依据用户openid查询公告信息
 */
exports.main = async (event, context) => {
  const { OPENID } = cloud.getWXContext()
  const res = await db.collection('notice')
    .aggregate()
    .match({ _openid: OPENID })
    .lookup({
      from: 'request',
      let: {
        notice_id: '$_id'
      },
      pipeline: $.pipeline()
        .match(_.expr($.and([
          $.eq(['$notice_id', '$$notice_id']),
          $.eq(['$status', 0])
        ])))
        .count('news')
        .project({
          news: 1
        })
        .done(),
      as: 'requests'
    })
    .replaceRoot({
      newRoot: $.mergeObjects([ $.arrayElemAt(['$requests', 0]), '$$ROOT' ])
    })
    .project({
      requests: 0
    })
    .sort({
      status: -1,
      update: -1
    })
    .end()

  if (res.errMsg === 'collection.aggregate:ok') {
    return {
      code: 0,
      data: res.list
    }
  } else {
    return {
      code: -1,
      errMsg: res.errMsg
    }
  }
}